package service

import (
	"time"
	"github.com/zhulizhe/golang-shortlink/internal/model"
	"github.com/zhulizhe/golang-shortlink/internal/repository"
	"github.com/zhulizhe/golang-shortlink/pkg/shortener"
)

type LinkService struct {
	repo repository.LinkRepository
}

func NewLinkService(repo repository.LinkRepository) *LinkService {
	return &LinkService{repo: repo}
}

func (s *LinkService) CreateShortLink(originalURL string) *model.Link {
	shortKey := shortener.GenerateShortLink(6)
	link := &model.Link{
		ShortKey:    shortKey,
		OriginalURL: originalURL,
		CreatedAt:   time.Now(),
		VisitCount:  0,
	}
	s.repo.Save(link)
	return link
}

func (s *LinkService) GetOriginalURL(shortKey string) (string, bool) {
	link, ok := s.repo.Get(shortKey)
	if !ok {
		return "", false
	}
	s.repo.IncrVisit(shortKey)
	return link.OriginalURL, true
}

func (s *LinkService) GetStats(shortKey string) (*model.Link, bool) {
	return s.repo.Get(shortKey)
}
